<template>
	<view class="editArticle-wrap">
		<view class="editArticle-title">
			<input class="editArticle-input" type="text" v-model="formData.title" placeholder="请输入文章标题" />
			<view class="editArticle-filter"><u-sl-filter v-if="menuList[0].show" :menuList="menuList" independence @result="flFilter"></u-sl-filter></view>
		</view>

		<u-mp-html ref="article" :content="formData.content" :editable="editable" />

		<view class="editor_toolbox">
			<i class="iconfont icon-undo" data-method="undo" @tap="edit" />
			<i class="iconfont icon-redo" data-method="redo" @tap="edit" />
			<i class="iconfont icon-img" data-method="insertImg" @tap="edit" />
			<i class="iconfont icon-video" data-method="insertVideo" @tap="edit" />
			<i class="iconfont icon-link" data-method="insertLink" @tap="edit" />
			<i class="iconfont icon-text" data-method="insertText" @tap="edit" />
			<i class="iconfont icon-clear" @tap="clear" />
			<i class="iconfont icon-save" @tap="save" />
		</view>

		<block v-if="modal">
			<view class="mask" />
			<view class="modal">
				<view class="modal_title">{{ modal.title }}</view>
				<input class="modal_input" :value="modal.value" maxlength="-1" auto-focus @input="modalInput" />
				<view class="modal_foot">
					<view class="modal_button" @tap="modalCancel">取消</view>
					<view class="modal_button" style="color:#576b95;border-left:1px solid rgba(0,0,0,.1)" @tap="modalConfirm">确定</view>
				</view>
			</view>
		</block>

		<u-bottom-button v-if="!id" type="2" value1="存为草稿" value2="发布文章" @clickOne="saveArticle(0)" @clickTwo="saveArticle(1)"></u-bottom-button>
		<u-bottom-button v-if="id && status == 0" type="2" value1="保存草稿" value2="发布文章" @clickOne="updateArticle(0)" @clickTwo="saveArticle(1)"></u-bottom-button>
		<u-bottom-button v-if="id && status == 1" type="2" value1="存为草稿" value2="保存文章" @clickOne="saveArticle(0)" @clickTwo="updateArticle(1)"></u-bottom-button>
	</view>
</template>

<script>
import uBottomButton from '@/components/u-bottom-button/u-bottom-button.vue';
import uMpHtml from '@/components/u-mp-html/u-mp-html';
import uSlFilter from '@/components/u-sl-filter/u-sl-filter.vue';
import { apiUrl } from '../../config';
export default {
	components: {
		uMpHtml,
		uBottomButton,
		uSlFilter
	},
	data() {
		return {
			modal: null,
			editable: true,
			formData: {
				banner: '',
				status: 0, //0草稿  1发布
				title: '',
				content: '',
				category: 0
			},
			menuList: [
				{
					show: false,
					title: '分类',
					key: 'fl',
					isSort: true,
					isMutiple: false,
					defaultSelectedIndex: 0,
					reflexTitle: true,
					detailList: []
				}
			],

			id: null, //文章id
			status: null
		};
	},
	onLoad(option) {
		this.id = option.id ? option.id : null;

		if (this.id) {
			this.articleDetailSysById();
		}
		this.queryDictItemsByCode();
	},
	onShow() {},
	onReady() {
		/**
		 * @description 设置获取链接的方法
		 * @param {String} type 链接的类型（img/video/audio/link）
		 * @param {String} value 修改链接时，这里会传入旧值
		 * @returns {Promise} 返回线上地址
		 *   type 为音视频时可以返回一个数组作为源地址
		 *   type 为 audio 时，可以返回一个 object，包含 src、name、author、poster 等字段
		 */
		this.$refs.article.getSrc = (type, value) => {
			return new Promise((resolve, reject) => {
				if (type === 'img') {
					uni.showActionSheet({
						itemList: ['本地选取', '远程链接'],
						success: res => {
							// 本地选取
							if (res.tapIndex === 0) {
								uni.chooseImage({
									count: 1,
									success: res => {
										//实际使用时，这里需要上传到服务器后返回
										uni.showLoading({
											title: '上传中'
										});

										uni.uploadFile({
											url: apiUrl + '/aos/api/qiniu/upload',
											name: 'file',
											filePath: res.tempFilePaths[0],
											formData: {},
											header: {},
											success: uploadFileRes => {
												const res = JSON.parse(uploadFileRes.data);
												this.formData.banner = res.result.url;
												resolve(res.result.url); // 返回线上地址
											},
											fail: reject,
											complete: () => {
												uni.hideLoading();
											}
										});

										// resolve(res.tempFilePaths[0]);
									},
									fail: reject
								});
								// 远程链接
							} else {
								this.callback = {
									resolve,
									reject
								};
								this.$set(this, 'modal', {
									title: '图片链接',
									value
								});
							}
						}
					});
				} else {
					this.callback = {
						resolve,
						reject
					};
					let title;
					if (type === 'video') title = '视频链接';
					else if (type === 'audio') title = '音频链接';
					else if (type === 'link') title = '链接地址';
					this.$set(this, 'modal', {
						title,
						value
					});
				}
			});
		};
	},
	methods: {
		//查询文章详情
		articleDetailSysById() {
			this.$api
				.articleDetailSysById({
					params: {
						id: this.id
					}
				})
				.then(res => {
					if (res.code == 200) {
						this.formData = res.result;
						this.status = res.result.status;
						
						this.menuList[0].defaultSelectedIndex = res.result.category;
					}
				});
		},

		//表单参数校验
		checkFormData() {
			let b = true;
			if (!this.formData.title) {
				uni.showToast({
					title: '标题未填写',
					icon: 'none'
				});
				b = false;
			}
			if (!this.formData.content) {
				uni.showToast({
					title: `内容未填写`,
					icon: 'none'
				});
				b = false;
			}
			if (!this.formData.banner) {
				uni.showToast({
					title: `至少上传一张图片作为封面`,
					icon: 'none'
				});
				b = false;
			}
			return b;
		},
		
		
		
		//保存草稿、保存文章
		updateArticle(status) {
			this.formData.content = this.$refs.article.getContent();
			
			if(!this.checkFormData()){
				return
			}
			this.formData.status = status;
			const message = status == 0 ? '保存草稿' : '保存文章';
			uni.showModal({
				title: `确认要${message}吗？`,
				success: res => {
					if (res.confirm) {
						this.$api
							.updateArticle({
								data: this.formData
							})
							.then(res => {
								if (res.code == 200) {
									uni.showToast({
										title: `${message}成功`,
										icon: 'none'
									});
									uni.navigateBack({
										delta: 1
									});
								} else {
									uni.showToast({
										title: res.message,
										icon: 'none'
									});
								}
							});
					}
				}
			});
		},
		
		

		//存为草稿、发布文章
		saveArticle(status) {
			this.formData.content = this.$refs.article.getContent();
			if(!this.checkFormData()){
				return
			}
			this.formData.status = status;
			const message = status == 0 ? '存为草稿' : '发布文章';
			uni.showModal({
				title: `确认要${message}吗？`,
				success: res => {
					if (res.confirm) {
						this.$api
							.addArticle({
								data: this.formData
							})
							.then(res => {
								if (res.code == 200) {
									uni.showToast({
										title: `${message}成功`,
										icon: 'none'
									});
									uni.navigateBack({
										delta: 1
									});
								} else {
									uni.showToast({
										title: res.message,
										icon: 'none'
									});
								}
							});
					}
				}
			});
		},

		//文章分类
		queryDictItemsByCode() {
			this.$api
				.queryDictItemsByCode({
					params: {
						code: 'article_category'
					}
				})
				.then(res => {
					this.formData.category = parseInt(res[0].value);
					this.menuList[0].detailList = res;
					this.menuList[0].show = true;
				});
		},

		flFilter(e) {
			this.menuList[0].defaultSelectedIndex = e.fl;
			this.formData.category = parseInt(e.fl);
		},

		// 处理模态框
		modalInput(e) {
			this.value = e.detail.value;
		},
		modalConfirm() {
			this.callback.resolve(this.value || this.modal.value || '');
			this.$set(this, 'modal', null);
		},
		modalCancel() {
			this.callback.reject();
			this.$set(this, 'modal', null);
		},
		// 调用编辑器接口
		edit(e) {
			this.$refs.article[e.currentTarget.dataset.method]();
		},
		// 清空编辑器内容
		clear() {
			uni.showModal({
				title: '确认',
				content: '确定清空内容吗？',
				success: res => {
					if (res.confirm) this.$refs.article.clear();
				}
			});
		},
		// 保存编辑器内容
		save() {
			var content = this.$refs.article.getContent();
			uni.showModal({
				title: '保存',
				content,
				confirmText: '完成',
				success: res => {
					if (res.confirm) {
						// 复制到剪贴板
						uni.setClipboardData({
							data: content
						});
						// 结束编辑
						this.editable = false;
					}
				}
			});
		}
	}
};
</script>

<style lang="less">
@import './editArticle.less';
</style>
